<?php
declare (strict_types = 1);

namespace app\common\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;
use think\facade\Env;
use think\helper\Str;

class Curd extends Command
{

    protected $appPath;

    // view 默认的两个模板
    protected $views = ['index', 'edit'];

    //字段内容
    protected $views_param = [
        'index' => "{field: '%key%', title: '%name%', align:'center'},",
        'search' => '
                        <div class="layui-inline">
                            <input type="text" name="%key%" placeholder="请输入%name%" autocomplete="off" class="layui-input">
                        </div>',
        'edit' => '
    <div class="layui-form-item">
        <label class="layui-form-label">%name%</label>
        <div class="layui-input-block">
            <input type="text" name="%key%"  placeholder="请输入%name%"  value="{:isset($list.%key%)?$list.%key%:\'\'}" lay-reqtext="请输入%name%" class="layui-input">
        </div>
    </div>'
    ];

    public function __construct()
    {
        parent::__construct();
        $this->appPath = base_path();
    }

    protected function configure()
    {
        // 指令配置
        $this->setName('make:curd')
            ->addArgument('parameter', Argument::OPTIONAL, "parameter name")
            ->addOption('module', null, Option::VALUE_REQUIRED, 'module name')
            ->setDescription('Create curd option parameter model --module?');
    }

    protected function execute(Input $input, Output $output)
    {
        // 首先获取默认模块
        $moduleName = config('app.default_app');
        $parameterName = trim($input->getArgument('parameter'));
        if (!$parameterName) {
            $output->writeln('parameter Name Must Set, it is  controller and model and validate of name');
            exit;
        }

        if ($input->hasOption('module')) {
            $moduleName = $input->getOption('module');
        }

        //下划线转驼峰
        $parameterName = Str::studly($parameterName);

        $this->makeController($parameterName, $moduleName);
        $this->makeService($parameterName, $moduleName);
        $this->makeModel($parameterName, $moduleName);
        $this->makeView($parameterName, $moduleName);
        $this->makeValidate($parameterName, $moduleName);

        $output->writeln($parameterName . ' controller create success');
        $output->writeln($parameterName . ' model create success');
        $output->writeln($parameterName . ' view create success');
        $output->writeln($parameterName . ' validate create success');

    }


    // 创建控制器文件
    protected function makeController($controllerName, $moduleName)
    {
        $controllerStub = $this->appPath .'common' . DIRECTORY_SEPARATOR . 'command' . DIRECTORY_SEPARATOR . 'curd' .DIRECTORY_SEPARATOR. 'Controller.stub';
        $controllerStub = str_replace(['$controller', '$module'], [ucfirst($controllerName), strtolower($moduleName)], file_get_contents($controllerStub));
        $controllerPath = $this->appPath . 'admin' . DIRECTORY_SEPARATOR . 'controller' . DIRECTORY_SEPARATOR;
        if (!is_dir($controllerPath)) {
            mkdir($controllerPath, 0777, true);
        }
        return file_put_contents( $controllerPath . ucfirst($controllerName) . '.php', $controllerStub);
    }

    //创建服务service文件
    protected  function makeService($serviceName, $moduleName){
        $modelStub = $this->appPath .'common' . DIRECTORY_SEPARATOR . 'command' . DIRECTORY_SEPARATOR . 'curd' . DIRECTORY_SEPARATOR . 'Service.stub';
        $modelPath = $this->appPath . $moduleName . DIRECTORY_SEPARATOR . 'service';
        if (!is_dir($modelPath)) {
            mkdir($modelPath, 0777, true);
        }
        $modelStub = str_replace(['$service', '$module'], [ucfirst($serviceName), strtolower($moduleName)], file_get_contents($modelStub));
        return file_put_contents($modelPath . DIRECTORY_SEPARATOR . ucfirst($serviceName) . 'Service.php', $modelStub);
    }

    // 创建模型文件
    public function makeModel($modelName, $moduleName)
    {
        $modelStub = $this->appPath .'common' . DIRECTORY_SEPARATOR . 'command' . DIRECTORY_SEPARATOR . 'curd' . DIRECTORY_SEPARATOR . 'Model.stub';
        $modelPath = $this->appPath . $moduleName . DIRECTORY_SEPARATOR . 'model';
        if (!is_dir($modelPath)) {
            mkdir($modelPath, 0777, true);
        }
        $modelStub = str_replace(['$model', '$module'], [ucfirst($modelName), strtolower($moduleName)], file_get_contents($modelStub));
        return file_put_contents($modelPath . DIRECTORY_SEPARATOR . ucfirst($modelName) . '.php', $modelStub);
    }

    // 创建验证器文件
    public function makeValidate($validateName, $moduleName)
    {
        $modelStub = $this->appPath .'common' . DIRECTORY_SEPARATOR . 'command' . DIRECTORY_SEPARATOR . 'curd' . DIRECTORY_SEPARATOR . 'Validate.stub';
        $modelPath = $this->appPath . $moduleName . DIRECTORY_SEPARATOR . 'validate';
        if (!is_dir($modelPath)) {
            mkdir($modelPath, 0777, true);
        }
        $modelStub = str_replace(['$validate', '$module'], [ucfirst($validateName), strtolower($moduleName)], file_get_contents($modelStub));
        return file_put_contents($modelPath . DIRECTORY_SEPARATOR . ucfirst($validateName) . '.php', $modelStub);
    }

    // 创建模板
    public function makeView($parameterName, $moduleName)
    {
        // 创建视图路径
        $viewPath =  root_path()  . 'view' . DIRECTORY_SEPARATOR .$moduleName.DIRECTORY_SEPARATOR. strtolower($parameterName);
        if (!is_dir($viewPath)) {
            mkdir($viewPath, 0777, true);
        }

        foreach ($this->views as $view) {
            // 视图模板源文件
            $viewStub = $this->appPath.'common' . DIRECTORY_SEPARATOR  . 'command' . DIRECTORY_SEPARATOR . 'curd' . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . $view.'.stub';
            $cols = '';
            $search = '';

            //如果数据库里面存在这表
            $exist = Db::query('show tables like "'.Env::get('database.prefix', 'think_').strtolower($parameterName).'"');
            if (count($exist)>0){
                $fields = Db::query("SHOW FULL COLUMNS FROM ".Env::get('database.prefix', 'think_').strtolower($parameterName));
                foreach ($fields as $field){
                    if ($field['Key']==''&&$field['Comment']!=''){
                        $cols .= (($view=='index'&&$cols!='')?"\r\t\t\t\t":"").str_replace(['%key%','%name%'], [$field['Field'],$field['Comment']],  $this->views_param[$view]);

                        //如果是index页面加入搜索器生成
                        if ($view=='index'){
                            $search .= str_replace(['%key%','%name%'], [$field['Field'],$field['Comment']],  $this->views_param['search']);
                        }
                    }
                }
            }

            // 创建文件
            $viewStub = str_replace(['$controller','$cols','$search'], [strtolower($parameterName),$cols,$search], file_get_contents($viewStub));
            file_put_contents($viewPath . DIRECTORY_SEPARATOR . $view . '.html', $viewStub);
        }

    }

}
